<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="景区门票预订id" prop="scenicBookingId">
        <el-input
          v-model="queryParams.scenicBookingId"
          placeholder="请输入景区门票预订id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="景区id" prop="areaId">
        <el-select
          v-model="queryParams.areaId"
          placeholder="请输入景区id"
          clearable
          @keyup.enter.native="handleQuery">
          <el-option
            v-for="area in scenicAreas"
            :key="area.areaId"
            :label="`${area.areaId} - ${area.areaName}`"
            :value="area.areaId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="游览时间">
        <el-date-picker
          v-model="daterangeTripData"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="游览人数" prop="tripCount">
        <el-input
          v-model="queryParams.tripCount"
          placeholder="请输入游览人数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总价" prop="totalPrice">
        <el-input
          v-model="queryParams.totalPrice"
          placeholder="请输入总价"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付状态" prop="paymentStatus">
        <el-select v-model="queryParams.paymentStatus" placeholder="请选择支付状态" clearable :default-value="0" :disabled=true>
          <el-option
            v-for="dict in dict.type.payment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['booking:scenebook:add']"
        >门票预订</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['booking:scenebook:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['booking:scenebook:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['booking:scenebook:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scenebookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="景区门票预订id" align="center" prop="scenicBookingId" />
      <el-table-column label="用户id" align="center" prop="userId" />
      <el-table-column label="景区id" align="center" prop="areaId" />
      <el-table-column label="游览时间" align="center" prop="tripData" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.tripData, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="游览人数" align="center" prop="tripCount" />
      <el-table-column label="总价" align="center" prop="totalPrice" />
      <el-table-column label="支付状态" align="center" prop="paymentStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_status" :value="scope.row.paymentStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.paymentStatus !== 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['booking:scenebook:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.paymentStatus !== 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['booking:scenebook:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.paymentStatus !== 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handlePay(scope.row)"
            v-hasPermi="['booking:scenebook:pay']"
          >支付</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" :visible.sync="updatePay" width="500px" append-to-body>
      <p>{{ sentence }}</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPay">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改景区门票预订对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" :disabled=true />
        </el-form-item>
        <el-form-item label="景区id" prop="areaId">
          <el-select v-model="form.areaId" placeholder="请输入景区id" @change="handleAreaChange">
            <el-option
              v-for="area in scenicAreas"
              :key="area.areaId"
              :label="`${area.areaId} - ${area.areaName}`"
              :value="area.areaId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="游览时间" prop="tripData">
          <el-date-picker clearable
            v-model="form.tripData"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择游览时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="游览人数" prop="tripCount" >
          <el-input v-model="form.tripCount" placeholder="请输入游览人数" @input="calculateTotalPrice()" />
        </el-form-item>
        <el-form-item label="总价" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入总价" :disabled=true />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScenebook, getScenebook, delScenebook, addScenebook, updateScenebook } from "@/api/booking/scenebook";
import { getid } from "@/api/booking/getid";
import { listScenicarea,getScenicarea } from "@/api/tourss/scenicarea/area";

export default {
  name: "Scenebook",
  dicts: ['payment_status'],
  data() {
    return {
      scenicAreas: [],
      ticket: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 景区门票预订表格数据
      scenebookList: [],
      // 弹出层标题
      title: "",
      sentence: '',
      // 是否显示弹出层
      open: false,
      updatePay : false,
      // 支付状态时间范围
      daterangeTripData: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scenicBookingId: null,
        userId: null,
        areaId: null,
        tripData: null,
        tripCount: null,
        totalPrice: null,
        paymentStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        areaId: [
          { required: true, message: "景区id不能为空", trigger: "blur" }
        ],
        tripData: [
          { required: true, message: "游览时间不能为空", trigger: "blur" }
        ],
        tripCount: [
          { required: true, message: "游览人数不能为空", trigger: "blur" }
        ],
        totalPrice: [
          { required: true, message: "总价不能为空", trigger: "blur" }
        ],
        paymentStatus: [
          { required: true, message: "支付状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.fetchScenicAreas();
  },
  methods: {
    /** 查询景区门票预订列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeTripData && '' != this.daterangeTripData) {
        this.queryParams.params["beginTripData"] = this.daterangeTripData[0];
        this.queryParams.params["endTripData"] = this.daterangeTripData[1];
      }
      listScenebook(this.queryParams).then(response => {
        this.scenebookList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    fetchScenicAreas() {
      listScenicarea().then(response => {
        this.scenicAreas = response.rows; // 假设返回的数据结构中有 areaId 和 areaName 字段
      }).catch(error => {
        console.error('获取景区列表失败：', error);
      });
    },
    getScenePrice(areaId){
      return new Promise((resolve, reject) => {
        getScenicarea(areaId).then(response => {
          this.ticket = response.data.ticketPrice;
          resolve(); // 票价获取成功，解析 Promise
        }).catch(error => {
          console.error('获取总价失败：', error);
          reject(error); // 处理获取票价失败的情况
        });
      });
    },
    calculateTotalPrice(){
      if (this.form.tripCount && this.ticket) {
        this.form.totalPrice = this.form.tripCount * this.ticket;
      } else {
        this.form.totalPrice = null;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.updatePay = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scenicBookingId: null,
        userId: null,
        areaId: null,
        tripData: null,
        tripCount: null,
        totalPrice: null,
        paymentStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeTripData = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAreaChange(){
      this.getScenePrice(this.form.areaId).then(() => {
        this.calculateTotalPrice(); // 在获取票价后计算总价
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scenicBookingId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getid().then(response => {
        this.form.userId = response.data; // 假设返回的数据结构中有 userId 字段
        this.open = true;
        this.title = "添加景区门票预订";
      }).catch(error => {
        console.error('获取 userId 失败：', error);
        // 处理获取 userId 失败的情况
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const scenicBookingId = row.scenicBookingId || this.ids
      getScenebook(scenicBookingId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改景区门票预订";
      });
    },
    handlePay(row){
      this.form=row
      this.data=row.totalPrice;
      this.sentence = `支付后不可再修改订单信息，确认支付 ${this.data} ？`;
      this.updatePay = true;
      this.title = "支付界面";
    },
    submitPay() {
      this.form.paymentStatus=1;
      updateScenebook(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.updatePay = false;
        this.getList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.scenicBookingId != null) {
            updateScenebook(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.paymentStatus=0;
            addScenebook(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scenicBookingIds = row.scenicBookingId || this.ids;
      this.$modal.confirm('是否确认删除景区门票预订编号为"' + scenicBookingIds + '"的数据项？').then(function() {
        return delScenebook(scenicBookingIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('booking/scenebook/export', {
        ...this.queryParams
      }, `scenebook_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
